<template>
  <div class="myparams-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 警告框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false">
      </el-alert>
      <div class="block">
        <span class="demonstration">选择商品分类：</span>
        <el-cascader v-model="parentCategoriesArray" :options="categoriesList" :props="categoriesProps"
          @change="handleChange">
        </el-cascader>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数按钮 -->
          <el-button type="primary" @click="" size="mini" :disabled="parentCategoriesArray.length!==3"
            @click="openAddManyParam">添加参数
          </el-button>
          <!-- 添加动态参数对话框 -->
          <el-dialog title="添加动态参数" :visible.sync="addManyParamDialogVisible" width="50%" :before-close="handleClose">
            <el-form ref="manyParamFormRef" :rules="manyParamFormRules" :model="manyParamForm" label-width="100px">
              <el-form-item label="动态参数：" prop="attr_name">
                <el-input v-model="manyParamForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addManyParamDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addManyParam">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 编辑动态参数对话框 -->
          <el-dialog title="修改动态参数" :visible.sync="editManyParamDialogVisible" width="50%" :before-close="handleClose">
            <el-form ref="editmanyParamFormRef" :rules="manyParamFormRules" :model="editManyParamForm"
              label-width="100px">
              <el-form-item label="动态参数：" prop="attr_name">
                <el-input v-model="editManyParamForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editManyParamDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editManyParams">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 动态参数列表 -->
          <el-table :data="manyParamsList" border style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="24">
                    <div class="grid-content bg-purple-dark">
                      <el-tag closable @close="handleDelete(index,scope.row)"
                        v-for="(item,index) in scope.row.attr_vals" :key="index">
                        {{item}}
                      </el-tag>
                      <!-- New Tag -->
                      <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                        ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)">
                      </el-input>
                      <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                      </el-button>
                    </div>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="openEditManyParams(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteManyParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性按钮 -->
          <el-button type="primary" @click="openAddOnlyParam" size="mini" :disabled="parentCategoriesArray.length!==3">
            添加属性</el-button>
          <!-- 添加静态属性对话框 -->
          <el-dialog title="添加静态属性" :visible.sync="addOnlyParamDialogVisible" width="50%" :before-close="handleClose">
            <el-form ref="onlyParamFormRef" :rules="onlyParamFormRules" :model="onlyParamForm" label-width="100px">
              <el-form-item label="静态属性：" prop="attr_name">
                <el-input v-model="onlyParamForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addOnlyParamDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addOnlyParam">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 编辑静态属性对话框 -->
          <el-dialog title="修改静态属性" :visible.sync="editOnlyParamDialogVisible" width="50%" :before-close="handleClose">
            <el-form ref="editOnlyParamFormRef" :rules="onlyParamFormRules" :model="editOnlyParamForm"
              label-width="100px">
              <el-form-item label="静态属性：" prop="attr_name">
                <el-input v-model="editOnlyParamForm.attr_name"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editOnlyParamDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editOnlyParams">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 静态属性列表 -->
          <el-table :data="onlyParamsList" border style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="24">
                    <div class="grid-content bg-purple-dark">
                      <el-tag closable @close="handleDelete(index,scope.row)"
                        v-for="(item,index) in scope.row.attr_vals" :key="index">
                        {{item}}
                      </el-tag>
                      <!-- New Tag -->
                      <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                        ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)">
                      </el-input>
                      <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                      </el-button>
                    </div>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="openEditOnlyParams(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" @click="deleteOnlyParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

  </div>
</template>
<script>
  export default {
    name: 'MyParams',
    data() {
      return {
        onlyParamFormRules: {
          attr_name: [{
            required: true,
            message: '请输入属性名称',
            trigger: 'blur'
          }]
        },
        manyParamFormRules: {
          attr_name: [{
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }]
        },
        manyParamForm: {
          attr_name: '',
          attr_sel: 'many',
          attr_vals: ''
        },
        onlyParamForm: {
          attr_name: '',
          attr_sel: 'only'
        },
        selectedId: 0,
        activeName: 'many',
        categoriesList: [],
        parentCategoriesArray: [],
        categoriesProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          expandTrigger: 'hover'
        },
        manyParamsList: [],
        onlyParamsList: [],
        selecteManyParamdId: 0,
        selecteOnlyParamdId: 0,
        editManyParamForm: {
          attr_name: '',
          attr_sel: '',
          attr_vals: ''
        },
        editOnlyParamForm: {
          attr_name: '',
          attr_sel: '',
          attr_vals: ''
        },
        addManyParamDialogVisible: false,
        addOnlyParamDialogVisible: false,
        editManyParamDialogVisible: false,
        editOnlyParamDialogVisible: false,
        inputVisible: false,
        inputValue: ''
      }
    },
    created() {
      this.initCategoriesList()
    },
    methods: {
      async initCategoriesList() {
        const {
          data: res
        } = await this.$http.get('categories', )
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取商品分类失败',
            type: 'error'
          })
        } else {
          this.categoriesList = res.data
        }
      },
      handleChange() {
        this.getParams()
      },
      handleClick() {
        this.getParams()
      },

      async getParams() {
        if (this.parentCategoriesArray.length !== 3) {
          this.parentCategoriesArray = []
          this.manyParamsList = []
          this.onlyParamsList = []
          return
        }
        this.selectedId = this.parentCategoriesArray[this.parentCategoriesArray.length - 1]
        const {
          data: res
        } = await this.$http.get(`categories/${this.selectedId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyParamsList = res.data
        } else {
          this.onlyParamsList = res.data
        }
      },
      openAddManyParam() {
        this.addManyParamDialogVisible = true
      },
      addManyParam() {
        this.$refs.manyParamFormRef.validate(async valid => {
          if (!valid) {
            this.$message({
              showClose: true,
              message: '提交的数据非法',
              type: 'error'
            })
          } else {
            const {
              data: res
            } = await this.$http.post(`categories/${this.selectedId}/attributes`, this.manyParamForm)
            if (res.meta.status !== 201) {
              this.$message({
                showClose: true,
                message: '添加动态参数失败',
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: '添加动态参数成功',
                type: 'success'
              })
              this.addManyParamDialogVisible = false
              this.$refs.manyParamFormRef.resetFields()
              this.getParams()
            }
          }
        })
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      openAddOnlyParam() {
        this.addOnlyParamDialogVisible = true
      },
      addOnlyParam() {
        this.$refs.onlyParamFormRef.validate(async valid => {
          if (!valid) {
            this.$message({
              showClose: true,
              message: '提交的数据非法',
              type: 'error'
            })
          } else {
            const {
              data: res
            } = await this.$http.post(`categories/${this.selectedId}/attributes`, this.onlyParamForm)
            if (res.meta.status !== 201) {
              this.$message({
                showClose: true,
                message: '添加静态属性失败',
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: '添加静态属性成功',
                type: 'success'
              })
              this.addOnlyParamDialogVisible = false
              this.$refs.onlyParamFormRef.resetFields()
              this.getParams()
            }
          }
        })
      },
      deleteManyParams(param) {
        this.$confirm('此操作将永久删除该动态参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {
            data: res
          } = await this.$http.delete(`categories/${this.selectedId}/attributes/${param.attr_id}`)
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: '删除动态参数失败',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '删除动态参数成功',
              type: 'success'
            })
            this.getParams()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      deleteOnlyParams(param) {
        this.$confirm('此操作将永久删除该静态属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {
            data: res
          } = await this.$http.delete(`categories/${this.selectedId}/attributes/${param.attr_id}`)
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: '删除静态属性失败',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '删除静态属性成功',
              type: 'success'
            })
            this.getParams()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      openEditManyParams(param) {
        this.editManyParamDialogVisible = true
        this.selecteManyParamdId = param.attr_id
        this.editManyParamForm.attr_name = param.attr_name
        this.editManyParamForm.attr_sel = param.attr_sel
        this.editManyParamForm.attr_vals = param.attr_vals
      },
      editManyParams() {
        this.$refs.editmanyParamFormRef.validate(async valid => {
          if (!valid) {
            this.$message({
              showClose: true,
              message: '提交的数据非法',
              type: 'error'
            })
          } else {
            const {
              data: res
            } = await this.$http.put(
              `categories/${this.selectedId}/attributes/${this.selecteManyParamdId}`, this
              .editManyParamForm)
            if (res.meta.status !== 200) {
              this.$message({
                showClose: true,
                message: '修改动态参数失败',
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: '修改动态参数成功',
                type: 'success'
              })
              this.editManyParamDialogVisible = false
              this.getParams()
            }
          }
        })
      },

      openEditOnlyParams(param) {
        this.editOnlyParamDialogVisible = true
        this.selecteOnlyParamdId = param.attr_id
        this.editOnlyParamForm.attr_name = param.attr_name
        this.editOnlyParamForm.attr_sel = param.attr_sel
        this.editOnlyParamForm.attr_vals = param.attr_vals
      },
      editOnlyParams() {
        this.$refs.editOnlyParamFormRef.validate(async valid => {
          if (!valid) {
            this.$message({
              showClose: true,
              message: '提交的数据非法',
              type: 'error'
            })
          } else {
            const {
              data: res
            } = await this.$http.put(
              `categories/${this.selectedId}/attributes/${this.selecteOnlyParamdId}`, this
              .editOnlyParamForm)
            if (res.meta.status !== 200) {
              this.$message({
                showClose: true,
                message: '修改静态属性失败',
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: '修改静态属性成功',
                type: 'success'
              })
              this.editOnlyParamDialogVisible = false
              this.getParams()
            }
          }
        })
      },

      showInput(row) {
        row.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },

      handleInputConfirm(row) {
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        } else {
          row.attr_vals.push(row.inputValue.trim())
          this.putAttrVals(row)
          row.inputValue = ''
          row.inputVisible = false
        }
      },
      // 修改attr_vals
      async putAttrVals(row) {
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.selectedId}/attributes/${row.attr_id}`, {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals: row.attr_vals.join(',')
          })
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '修改参数项失败',
            type: 'error'
          })
        } else {
          this.$message({
            showClose: true,
            message: '修改参数项成功',
            type: 'success'
          })
        }
      },
      handleDelete(index, row) {
        row.attr_vals.splice(index, 1)
        this.putAttrVals(row)
      }
    }
  }

</script>
<style lang="less" scoped>
  .box-card {
    margin-top: 15px;
    padding: 0;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;
  }

  .block {
    margin-top: 20px;
    margin-bottom: 10px
  }

  .el-tag {
    margin-left: 15px;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
